/**
 * Copyright (c) 2023 murenchao
 * taomu is licensed under Mulan PubL v2.
 * You can use this software according to the terms and conditions of the Mulan PubL v2.
 * You may obtain a copy of Mulan PubL v2 at:
 *       http://license.coscl.org.cn/MulanPubL-2.0
 * THIS SOFTWARE IS PROVIDED ON AN "AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND,
 * EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO NON-INFRINGEMENT,
 * MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE.
 * See the Mulan PubL v2 for more details.
 */
package cool.taomu.toolkit.jersey

import com.google.inject.Injector
import com.google.inject.Key
import com.google.inject.name.Names
import javax.inject.Inject
import javax.servlet.ServletContext
import org.apache.commons.lang3.StringUtils
import org.glassfish.hk2.api.ServiceLocator
import org.glassfish.jersey.server.ResourceConfig
import org.glassfish.jersey.server.mvc.freemarker.FreemarkerMvcFeature
import org.jvnet.hk2.guice.bridge.api.GuiceBridge
import org.jvnet.hk2.guice.bridge.api.GuiceIntoHK2Bridge
import org.slf4j.LoggerFactory
import org.glassfish.jersey.media.multipart.MultiPartFeature
import java.util.ArrayList

class GuiceResourceConfig extends ResourceConfig {
	val static LOG = LoggerFactory.getLogger(GuiceResourceConfig);

	new() {
		super();
	}

	@Inject
	new(ServiceLocator serviceLocator, ServletContext servletContext) {
		var injector = servletContext.getAttribute(Injector.name) as Injector;
		var pks = new ArrayList<String>();
		pks.add("io.swagger.jaxrs.listing");
		try {
			var String pk = injector.getInstance(Key.get(String, Names.named("jersery.packages")));
			pks.add(pk);
		} catch (Exception ex) {
			LOG.debug("packages Exception:{}", ex);
		}
		try {
			var String slpk = injector.getInstance(Key.get(String, Names.named("jersery.serviceloader.packages")));
			pks.add(slpk);
		} catch (Exception ex) {
			LOG.debug("packages Exception:{}", ex);
		}
		var pk = pks.join(",")
		LOG.info("packages:{}", pk);
		packages(pk.split(","));
		register(MultiPartFeature);
		try {
			var String tmpPath = injector.getInstance(Key.get(String, Names.named("jersery.template.path")));
			tmpPath = StringUtils.defaultIfBlank(tmpPath, "freemarker")
			LOG.info("页面模板路径：{}", tmpPath);
			property(FreemarkerMvcFeature.TEMPLATE_BASE_PATH, tmpPath);
		} catch (Exception ex) {
			LOG.debug("packages Exception:{}", ex);
			LOG.info("加载默认页面模板路径：freemarker");
			property(FreemarkerMvcFeature.TEMPLATE_BASE_PATH, "freemarker");
		}
		register(FreemarkerMvcFeature);
		GuiceBridge.getGuiceBridge().initializeGuiceBridge(serviceLocator);
		var GuiceIntoHK2Bridge guiceBridge = serviceLocator.getService(GuiceIntoHK2Bridge);
		guiceBridge.bridgeGuiceInjector(injector);

		register(io.swagger.jaxrs.listing.ApiListingResource);
		register(io.swagger.jaxrs.listing.AcceptHeaderApiListingResource);
		register(io.swagger.jaxrs.listing.SwaggerSerializers);

	}

}
